<?php
require_once('\Common\Validator.php');
require_once('\Models\Database.php');
require_once('\Models\DBConfig.php');
require_once('\Common\Strings.php');

class ManageUsersModel
{
	private $_db = null;
	
	public function __construct(Database $db)
	{
		$this->_db = $db;
	}
	
	/**
	 * Skapa en användare
	 * @param $user string
	 * @param $password string
	 * @param $repeatPassword string
	 * @param $minLength integer
	 * @return $output array felmeddelanden (tom om inga felmeddelanden)
	 */
	public function createUser($user, $password, $repeatPassword, $minLength)
	{
		$output = array();
		
		if(!Validator::ValidateUserName($user))
			$output[] = Strings::VALIDATION_USERNAME_INCORRECT;
		
		if(!Validator::ValidatePassword($password, $minLength))
			$output[] = Strings::VALIDATION_PASSWORD_INCORRECT;
		
		if(!Validator::CompareStrings($password, $repeatPassword))
			$output[] = Strings::VALIDATION_PASSWORD_MISMATCH;
				
		// Om användaren redan finns
		if ($this->userExists($user))
			$output[] = Strings::DB_USER_EXISTS;
		
		// Exekvera sql om inga fel uppstått
		if(count($output) == 0)
		{
			$sql = "INSERT INTO login (user, password) VALUES (?, ?)";
		
			$statement = $this->_db->Prepare($sql);
			
			$statement->bind_param("ss", $user, $password);
			
			$insertId = $this->_db->Insert($statement);
		}
		
		return $output;
	}
	
	/**
	 * Kontrollerar om samma användarnamn redan finns i DB
	 * @param $user string
	 * @param $loginID int
	 * @return bool
	 */
	public function userExists($user, $loginID = "")
	{
		$sql = "SELECT COUNT(*) FROM login WHERE user='$user' OR loginID='$loginID'";
		
		if($this->_db->SelectOne($sql) > 0)
			return true;
		else
			return false;
	}
	
	/**
	 * Tar bort en användare ur DB
	 * @param $loginID int
	 * @return bool
	 */
	public function deleteUser($id = "", $user = "")
	{
		if($user != "")
			$sql = "DELETE FROM login WHERE user='$user'";
		else if($id != "")
			$sql = "DELETE FROM login WHERE loginID='$id'";
		else
			return false;
		
		$statement = $this->_db->Prepare($sql);
		
		if($this->userExists($user,$id))
			return $this->_db->Delete($statement);
		else
			return false;
	}
}

?>